package com.github.tomakehurst.wiremock.admin.tasks;

import com.github.tomakehurst.wiremock.admin.AdminTask;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.common.url.PathParams;
import com.github.tomakehurst.wiremock.core.Admin;
import com.github.tomakehurst.wiremock.extension.export.StubExportHelper;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 兼容版单个导出任务：无 PathParams/RequestSpec 依赖，手动解析 URL
 * 对应接口：GET /__admin/mappings/{stubId}/export
 */
public class ExportSingleStubTask implements AdminTask {
    // 正则表达式：匹配 URL 中的 Stub ID（如 /__admin/mappings/123e4567-e89b-12d3-a456-426614174000/export）
    private static final Pattern STUB_ID_PATTERN = Pattern.compile("/mappings/export/([0-9a-fA-F\\-]+)");

    @Override
    public ResponseDefinition execute(Admin admin, ServeEvent serveEvent, PathParams pathParams) {
        // 1. 手动解析 URL 中的 Stub ID（替代 PathParams）
        if (serveEvent == null){
            return ResponseDefinitionBuilder.responseDefinition()
                    .withStatus(404)
                    .withBody("输入有误")
                    .build();
        }
        LoggedRequest request = serveEvent.getRequest();
        Matcher matcher = STUB_ID_PATTERN.matcher(request.getUrl());
        if (!matcher.matches()) {
            return ResponseDefinitionBuilder.responseDefinition()
                    .withStatus(400)
                    .withBody("URL 格式无效，正确格式： /__admin/mappings/export/{stubId}")
                    .build();
        }

        // 2. 提取并转换 Stub ID
        String stubIdStr = matcher.group(1);
        UUID stubId;
        try {
            stubId = UUID.fromString(stubIdStr);
        } catch (IllegalArgumentException e) {
            return ResponseDefinitionBuilder.responseDefinition()
                    .withStatus(400)
                    .withBody("Invalid Stub ID format: " + stubIdStr)
                    .build();
        }

        // 3. 原生 Admin 获取 Stub（2.x 及以上通用 API）
        StubMapping stub = admin.getStubMapping(stubId).getItem();
        if (stub == null) {
            return ResponseDefinitionBuilder.responseDefinition()
                    .withStatus(404)
                    .withBody("Stub not found. ID: " + stubId)
                    .build();
        }

        // 4. 构建下载响应（替代高版本 ResponseDefinition 构造）
        byte[] jsonBytes = StubExportHelper.exportSingle(stub);
        return ResponseDefinitionBuilder.responseDefinition()
                .withStatus(200)
                // 响应头：触发浏览器下载
                .withHeader("Content-Disposition", "attachment; filename=\"" + StubExportHelper.getSingleFileName(stub) + "\"")
                .withHeader("Content-Type", "application/json; charset=UTF-8")
                .withBody(jsonBytes) // 原生二进制响应体
                .build();
    }

}